package org.darkforest.merchant.controller;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.darkforest.common.services.StoreExtendsService;
import org.darkforest.common.util.AliOssFileUploadUtil;
import org.darkforest.common.services.DeliverService;
import org.darkforest.common.services.ModuleService;
import org.darkforest.common.util.Utils;
import org.darkforest.dao.mapper.StoreExtendMapper;
import org.darkforest.merchant.utils.JSONUtils;
import org.darkforest.model.Express;
import org.darkforest.model.StoreExtend;
import org.darkforest.model.WayBillData;
import org.darkforest.model.Waybill;
import org.darkforest.vo.StoreSellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by chenyu on 15/1/30.
 * 订单物流相关控制类
 */
@Controller
@RequestMapping(value="/module")
public class ModuleController {
    @Autowired
    private DeliverService deliverService;
    @Autowired
    private ModuleService moduleService;
    @Autowired
    private StoreExtendsService storeExtendsService;
    /**
     * 模板列表
     * @param request
     * @return
     */
    @RequestMapping(value = "moduleList")
    public ModelAndView orderList(HttpServletRequest request) {
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        StoreExtend storeExtend=storeExtendsService.selectByPrimaryKey(sellerVo.getStoreId());
        String express = null;
        if(storeExtend != null && StringUtils.isNotEmpty(storeExtend.getExpress())) {
            express = storeExtend.getExpress();
        }
        List companyList =null;
        if(express !=null){
            String[] list = express.split(",");
            if(list.length !=0){
                List nList = Arrays.asList(list);
                companyList = deliverService.selectAllOfExpress(nList);
            }
        }
        return new ModelAndView("module/moduleList", "companyList", companyList);
    }

    @RequestMapping(value = "selectBillList")
    public ModelAndView selectBillList(HttpServletRequest request,Express express,
                                       @RequestParam(required = false, defaultValue = "1") String p) {
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");

//        List billList = moduleService.selectAllUnUsedBill();
        Waybill waybill = new Waybill();
        waybill.setMyAndPreset(sellerVo.getStoreId());
//        waybill.setExpressId(express.geteId());
//        waybill
        waybill.setExpressName(Utils.encodeGetParam(express.geteName()));
        waybill.setStart(Integer.parseInt(p));
        waybill.setWaybillUsable(true);

        waybill.setResultList(moduleService.findListByCondition(waybill));
        ModelAndView modelAndView = new ModelAndView("module/selectBillList", "pageBean", waybill);
        modelAndView.addObject("express",express);

        return modelAndView;
    }

    @RequestMapping(value = "bind")
    public ModelAndView bind(HttpServletRequest request,Waybill waybill) {
        Integer expressId = waybill.getExpressId();
        Integer oldBlId = waybill.getWaybillId();
        waybill.setWaybillId(null);
        waybill.setExpressId(null);
        waybill.setExpressName(Utils.encodeGetParam(waybill.getExpressName()));
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        waybill.setStoreId(sellerVo.getStoreId());
        waybill.setWaybillUsable(true);
        List<Waybill> waybills = moduleService.findListByCondition(waybill);
        if(waybills.size()==0){
            waybill = moduleService.selectById(oldBlId);
            waybill.setExpressId(expressId);
            waybill.setWaybillId(null);
            waybill.setStoreId(sellerVo.getStoreId());
            moduleService.insertBill(waybill);

        }else if(waybills.size()==1){
            waybills.get(0).setExpressId(expressId);
            moduleService.updateBill(waybills.get(0));
        }else{
            waybills.get(0).setExpressId(expressId);
            moduleService.updateBill(waybills.get(0));

        }
        return new ModelAndView("redirect:/module/moduleList");
    }

    @RequestMapping(value = "set")
    public ModelAndView set(HttpServletRequest request,Waybill waybill) {
        Waybill waybill1 = moduleService.selectById(waybill.getWaybillId());
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        waybill.setStoreId(sellerVo.getStoreId());
        String data = waybill1.getWaybillData();
        WayBillData billData = null;
        if(data!=null&&!"".equals(data)){
            JSONObject jsonObject =  JSONUtils.toJSONObject(data);
            billData =  JSONUtils.toBean(jsonObject,WayBillData.class);
            waybill1.setBillData(billData);
        }
        return new ModelAndView("module/set","bill",waybill1);
    }

    @RequestMapping(value = "doSet")
    public ModelAndView doSet(HttpServletRequest request,Waybill waybill,WayBillData billData) {
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        String data  = JSONUtils.toJSONObject(billData).toString();
        waybill.setWaybillData(data);
        waybill.setStoreId(sellerVo.getStoreId());
        moduleService.updateBill(waybill);
        return new ModelAndView("redirect:/module/moduleList");
    }

    @RequestMapping(value = "defaults")
    public ModelAndView defaults(HttpServletRequest request,Waybill waybill) {
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        waybill.setStoreId(sellerVo.getStoreId());
        List list = moduleService.findListByCondition(waybill);
        Waybill tempBill = null;
        for(int i=0;i<list.size();i++){
           tempBill = (Waybill)list.get(i);
            tempBill.setWaybillUsable(false);
            moduleService.updateBill(tempBill);
        }
        waybill.setWaybillUsable(true);
        int ret  = moduleService.updateBill(waybill);
        return new ModelAndView("redirect:/module/moduleList");
    }

    @RequestMapping(value = "unbind")
    public ModelAndView unbind(HttpServletRequest request,Waybill waybill) {
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        waybill.setStoreId(sellerVo.getStoreId());
        waybill.setExpressId(null);
//        waybill.setWaybillUsable(false);
        int ret  = moduleService.updateUnbind(waybill);
        return new ModelAndView("redirect:/module/moduleList");
    }

    @RequestMapping(value = "design")
    public ModelAndView design(HttpServletRequest request,Waybill waybill) {
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        waybill.setStoreId(sellerVo.getStoreId());
        Waybill bill = moduleService.selectById(waybill.getWaybillId());
        String data = bill.getWaybillData();
        WayBillData billData = null;
        if(data!=null&&!"".equals(data)){
           JSONObject jsonObject =  JSONUtils.toJSONObject(data);
            billData =  JSONUtils.toBean(jsonObject,WayBillData.class);
            bill.setBillData(billData);
        }
        return new ModelAndView("module/design","bill",bill);
    }

    @RequestMapping(value = "saveDesign")
    public ModelAndView saveDesign(HttpServletRequest request,Waybill waybill,WayBillData billData) {
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        waybill.setStoreId(sellerVo.getStoreId());
        String data  = JSONUtils.toJSONObject(billData).toString();
        waybill.setWaybillData(data);
        moduleService.updateBill(waybill);
        return new ModelAndView("redirect:/module/billList");
    }

    @RequestMapping(value = "test")
    public ModelAndView test(HttpServletRequest request,Waybill waybill) {
        Waybill bill = moduleService.selectById(waybill.getWaybillId());
        String data = bill.getWaybillData();
        WayBillData billData = null;
        if(data!=null&&!"".equals(data)){
            JSONObject jsonObject =  JSONUtils.toJSONObject(data);
            billData =  JSONUtils.toBean(jsonObject,WayBillData.class);
            bill.setBillData(billData);
        }
        return new ModelAndView("module/test","bill",bill);
    }

    @RequestMapping(value = "edit")
    public ModelAndView edit(HttpSession session,Waybill waybill) {
        StoreSellerVo sellerVo= (StoreSellerVo)session.getAttribute("sellerInfo");
        Waybill bill = moduleService.selectById(waybill.getWaybillId());
        List companyList = deliverService.getStoreExpress(sellerVo.getStoreId());
        ModelAndView m = new ModelAndView("module/edit","bill",bill);
        m.addObject("companyList",companyList);
        return m;
    }

    @RequestMapping(value = "doEdit")
    public ModelAndView doEdit(Waybill waybill,MultipartFile waybillImage1,HttpSession session) {
        StoreSellerVo sellerVo= (StoreSellerVo)session.getAttribute("sellerInfo");
        waybill.setStoreId(sellerVo.getStoreId());
        if(waybillImage1!=null){
            String oldName = waybillImage1.getOriginalFilename();
            if(oldName!=null&&!"".equals(oldName)) {
                String end = oldName.substring(oldName.lastIndexOf("."));
                String name = new Date().getTime() + end;
                String begin = System.getProperty("user.dir");
                File targetFile = new File(begin, name);
                try {
                    waybillImage1.transferTo(targetFile);
                    AliOssFileUploadUtil.uploadPic(new Date().getTime() + "", name, targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    ModelAndView modelAndView = new ModelAndView("message");
                    modelAndView.addObject("msg", "模板图片保存失败，请重新提交!");
                    return modelAndView;
                }
                waybill.setWaybillImage(name);
            }

        }
        moduleService.updateBill(waybill);
        return new ModelAndView("redirect:/module/billList");
    }

    @RequestMapping(value = "delete")
    public ModelAndView delete(HttpServletRequest request,Waybill waybill) {
        int ret = moduleService.delectBill(waybill.getWaybillId());
        return new ModelAndView("redirect:/module/billList");
    }

    @RequestMapping(value = "billList")
    public ModelAndView billList(HttpServletRequest reques,
                                 @RequestParam(required = false, defaultValue = "1") String p) {
        StoreSellerVo sellerVo= (StoreSellerVo)reques.getSession().getAttribute("sellerInfo");
        Waybill waybill = new Waybill();
        waybill.setStart(Integer.parseInt(p));
        waybill.setPageSize(8);
//        waybill.setWaybillUsable(true);
        waybill.setStoreId(sellerVo.getStoreId());
        waybill.setResultList(moduleService.findListByCondition(waybill));
        return new ModelAndView("module/billList", "pageBean", waybill);
    }


    @RequestMapping(value = "addModule")
    public ModelAndView addModule(HttpSession session) {
//        List companyList = deliverService.selectAllUsedExpress();
        StoreSellerVo sellerVo= (StoreSellerVo)session.getAttribute("sellerInfo");
        List companyList = deliverService.getStoreExpress(sellerVo.getStoreId());

        return new ModelAndView("module/addModule", "companyList", companyList);
    }
    @RequestMapping(value = "doAddModule")
    public ModelAndView doAddModule(Waybill waybill,MultipartFile waybillImage1,HttpSession session) {
        StoreSellerVo sellerVo= (StoreSellerVo)session.getAttribute("sellerInfo");
        waybill.setStoreId(sellerVo.getStoreId());
        if(waybillImage1!=null){
            String oldName = waybillImage1.getOriginalFilename();
            if(oldName!=null&&!"".equals(oldName)) {
                String end = waybillImage1.getOriginalFilename().substring(waybillImage1.getOriginalFilename().lastIndexOf("."));
                String name = new Date().getTime()  + end;
                String begin = System.getProperty("user.dir");
                File targetFile = new File(begin, name);
                try {
                    waybillImage1.transferTo(targetFile);
                    AliOssFileUploadUtil.uploadPic(new Date().getTime() + "", name, targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    ModelAndView modelAndView = new ModelAndView("message");
                    modelAndView.addObject("msg", "模板图片保存失败，请重新提交!");
                    return modelAndView;
                }
                waybill.setWaybillImage(name);
            }
        }
        moduleService.insertBill(waybill);
        return new ModelAndView("redirect:/module/billList");
    }
}
